/**
 * Copyright (c) 2016 Lenovo Group
 * All Rights Reserved.
 * 
 * Project Name:app-gateway
 * Create Time: 2016年1月18日 下午6:27:16
 */
package com.lenovo.lmrp.server.appgateway.spi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.annotations.GZIP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lenovo.lmrp.api.appgateway.IAppPage;
import com.lenovo.lmrp.api.assigntrace.ITraceTicket;
import com.lenovo.lmrp.api.assigntrace.ITraceWorkflow;
import com.lenovo.lmrp.api.constant.CloseReason;
import com.lenovo.lmrp.api.constant.QueryEntity;
import com.lenovo.lmrp.api.eventrecorder.IEventQuery;
import com.lenovo.lmrp.api.itsmgateway.IItsmEngineer;
import com.lenovo.lmrp.api.itsmgateway.IItsmProject;
import com.lenovo.lmrp.api.itsmgateway.IItsmTicket;
import com.lenovo.lmrp.api.model.RestResponse;
import com.lenovo.lmrp.api.model.entity.ActivityFormPO;
import com.lenovo.lmrp.api.model.entity.ProjectPO;
import com.lenovo.lmrp.api.model.entity.TicketEventPO;
import com.lenovo.lmrp.api.model.entity.TicketPartsPO;
import com.lenovo.lmrp.api.model.view.AttachmentVO;
import com.lenovo.lmrp.api.model.view.ChangedTicketVO;
import com.lenovo.lmrp.api.model.view.EngineerVO;
import com.lenovo.lmrp.api.model.view.PartsVO;
import com.lenovo.lmrp.api.model.view.ProjectVO;
import com.lenovo.lmrp.api.model.view.TicketEventVO;
import com.lenovo.lmrp.api.model.view.TicketProcessVO;
import com.lenovo.lmrp.api.model.view.TicketVO;
import com.lenovo.lmrp.server.appgateway.AppSession;
import com.lenovo.lmrp.server.appgateway.RestClientFactory;
import com.lenovo.lmrp.server.appgateway.util.AppCache;
import com.lenovo.lmrp.server.appgateway.util.PageLoader;
import com.lenovo.sdc.framework.annotation.RestService;
import com.lenovo.sdc.framework.cache.CacheItem;
import com.lenovo.sdc.framework.rest.RestClientProxy;
import com.lenovo.sdc.framework.util.CommonUtil;
import com.lenovo.sdc.framework.util.JSONHelper;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * 
 * 
 * @author suo
 * @version $Id: AppPageImpl.java, v 0.1 2016年2月29日 上午9:44:48 suo Exp $
 */
@RestService
@GZIP
@Path("/app/v1")
@Produces("application/json;charset-utf-8")
@Consumes("application/json;charset-utf-8")
public class AppPageImpl implements IAppPage {

	private static final Logger log = LoggerFactory.getLogger(AppPageImpl.class);
	
	private AppSession appsession;
    private String token;

    @HeaderParam("Authorization")
    private void setToken(String authorization) {
        if (!CommonUtil.isNullOrEmpty(authorization)) {
            token = authorization.substring(6);
            CacheItem<AppSession> cache = AppCache.getClient().get(AppSession.class,token);
            appsession = cache.getValue();
        }
    }

	/**
	 * 
	 * 获取工单详情页
	 * 
	 * @author suo
	 * @see com.lenovo.lmrp.api.appgateway.IAppPage#getTicketPage(java.lang.String,
	 *      java.lang.String)
	 */
	@Override
	public Response getTicketPage(String itsmcode, String ticketid) {
		
		//获取当前操作工程师
	    String engineer = "";
	    if(Objects.nonNull(appsession)) {
	        engineer = appsession.getLoginData().getLoginname();
	    }
		List<TicketEventPO> ticketEventPOs = new ArrayList<>();
		RestClientProxy traceProxy = RestClientFactory.getAssignTraceClient();
		RestClientProxy eventProxy = RestClientFactory.getEventRecorderClient();
		RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
		
		if(Objects.nonNull(eventProxy)){
			IEventQuery eventQuery = eventProxy.getService(IEventQuery.class);
			if(Objects.nonNull(eventQuery)){
				RestResponse<List<TicketEventVO>> ticketEvents = eventQuery.getTicketEvents(itsmcode, ticketid);
				List<TicketEventVO> result = ticketEvents.getResult();
				if (Objects.nonNull(result)) {
				    result.forEach(vo -> {
	                    TicketEventPO tpo = new TicketEventPO();
	                    tpo.setAction(vo.getAction().toLowerCase());
	                    tpo.setEventTime(vo.getEventtime());
	                    tpo.setTicketID(vo.getTicketid());
	                    try {
	                        // the content of vo is JSON String
	                        if (Objects.nonNull(vo.getContent()))
	                            tpo.setContent(JSONHelper.fromJSON(vo.getContent(), Map.class));
	                    } catch (Exception e) {
	                        log.error(e.getMessage(), e);
	                    }
	                    ticketEventPOs.add(tpo);
	                });
				}
			}
		}
		ITraceTicket traceTicket = traceProxy.getService(ITraceTicket.class);
		ITraceWorkflow traceWorkflow = traceProxy.getService(ITraceWorkflow.class);
		IItsmTicket itsmTicket = itsmProxy.getService(IItsmTicket.class);
		HashMap<String, Object> scopes = new HashMap<String, Object>();
		String page = null;
		try {
			// 获取工单信息及扩展信息
			RestResponse<Object> ticketResp = traceTicket.getEntityDetail(itsmcode, QueryEntity.TICKET.name(), ticketid,
					null);
			//禁止工单被其他工程师打开编辑
			Map ticket = (Map)ticketResp.getResult();
			Object assignee = ticket.get("assignee");
			if(Objects.nonNull(assignee) && !String.valueOf(assignee).equals(engineer)){
				return null;
			}
			RestResponse<Object> ticketExResp = traceTicket.getEntityDetail(itsmcode, QueryEntity.TICKET_EXTENSE.name(),
					ticketid, null);
			// 获取流程节点
			RestResponse<TicketProcessVO> tpVOResp = traceWorkflow.getTicketProcessVO(itsmcode, ticketid);
			// 组合页面所需数据
			Map ticketEX = (Map) ticketExResp.getResult();
			Map<String, Object> ticketExtpropsMap = JSONHelper.fromJSON(ticketEX.get("extprops").toString(), Map.class);
			String respondLevel = ticketExtpropsMap.get("respondlevel").toString();
			if (CommonUtil.nonNullAndEmpty(respondLevel)) {
				String[] respondLevelArr = respondLevel.replace("*", "x").split("x");
				String respondTime = respondLevelArr[respondLevelArr.length - 1];
				scopes.put("respondTime", respondTime);
			}

			// 放入map
			scopes.put("ticket", ticketResp.getResult());
			scopes.put("ticketEx", ticketExtpropsMap);
			scopes.put("respondLevel", respondLevel);
			scopes.put("ticketProcess", tpVOResp.getResult());
			scopes.put("ticketEventPOs", ticketEventPOs);
			// 获取页面
			page = PageLoader.getPage("process/ticketDetails.html", scopes);

			//工单更新是否被查看
			int changenottobeview;
			if (ticketExtpropsMap.get("changenottobeview") == null)
				changenottobeview = 0;
			else
				changenottobeview = (Integer)ticketExtpropsMap.get("changenottobeview");
			//第一次查看之后设置成已查看状态
			if ( changenottobeview == 1 && itsmTicket != null) {
				Map<String, Object> extense = new HashMap<>();
				extense.put("changenottobeview", 0);
				itsmTicket.updateTicketExtense(itsmcode, ticketid, extense);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			page = e.getMessage();
		}
		return Response.ok(page, MediaType.TEXT_HTML_TYPE).build();
	}

	@Override
	public Response getProcessPage(String itsmcode, String ticketid) {
		// TODO Auto-generated method stub

		return null;
	}

	/**
	 * 
	 * 获取节点次级页面
	 * 
	 * @author suo
	 * @see com.lenovo.lmrp.api.appgateway.IAppPage#getActivePage(java.lang.String,
	 *      java.lang.String, java.lang.String)
	 */
	@Override
	public Response getActivePage(String token, String itsmcode, String ticketid, String activityid) {
		log.debug("ticket {} load {} page",ticketid,activityid);
		RestClientProxy traceProxy = RestClientFactory.getAssignTraceClient();
		ITraceTicket traceTicket = traceProxy.getService(ITraceTicket.class);
		ITraceWorkflow traceWorkflow = traceProxy.getService(ITraceWorkflow.class);
		HashMap<String, Object> scopes = new HashMap<String, Object>();
		String page = null;
		try {
			// 获取工单扩展信息
			RestResponse<Object> ticketExResp = traceTicket.getEntityDetail(itsmcode, QueryEntity.TICKET_EXTENSE.name(),
					ticketid, null);
			// 获取当前节点
			RestResponse<ActivityFormPO> activityResp = traceWorkflow.getWorkFlowActivity(itsmcode, activityid);
			Map ticketEX = (Map) ticketExResp.getResult();
			Map<String, String> ticketExtpropsMap = JSONHelper.fromJSON(ticketEX.get("extprops").toString(), Map.class);
			// 获取工程师信息
			RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
			IItsmEngineer iItsmEngineer = itsmProxy.getService(IItsmEngineer.class);
			try {
				Response response = iItsmEngineer.getEngineer(itsmcode,
						appsession.getLoginData().getLoginname());
				RestResponse rest = response.readEntity(RestResponse.class);
				scopes.put("engineer", (EngineerVO)rest.getResult(EngineerVO.class));
				response.close();				
			} catch (Exception e) {
				log.warn("activepage get engineer info error.",e);
			}
			// 工程师接单时间
			String pickuptime = ticketExtpropsMap.get("pickuptime");
			String actualcompletetime = ticketExtpropsMap.get("actualcompletetime");
			if (CommonUtil.nonNullAndEmpty(pickuptime)) {
				ticketExtpropsMap.put("formatpickuptime", this.format(pickuptime));
			}
			if (CommonUtil.nonNullAndEmpty(actualcompletetime)) {
				ticketExtpropsMap.put("formatactualcompletetime", this.format(actualcompletetime));
			}

			// 实际服务客户电话格式化 隐藏中间四位
			String actuallcustomerphone = ticketExtpropsMap.get("actuallcustomerphone");
			if (CommonUtil.nonNullAndEmpty(actuallcustomerphone)) {
				ticketExtpropsMap.put("actuallcustomerphone",
						actuallcustomerphone.substring(0, 3) + "****" + actuallcustomerphone.substring(7));
			}

			scopes.put("ticketEx", ticketExtpropsMap);
			scopes.put("ticketId", ticketid);
			page = PageLoader.getPage(activityResp.getResult().getActionForm(), scopes);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			page = e.getMessage();
		}
		return Response.ok(page, MediaType.TEXT_HTML_TYPE).build();
	}

	/**
	 * 
	 * 获取改约页面
	 * 
	 * @author suo
	 * @see com.lenovo.lmrp.api.appgateway.IAppPage#getChangeAppointment(java.lang.String,
	 *      java.lang.String, java.lang.String)
	 */
	@Override
	public Response getChangeAppointment(String itsmcode, String ticketid, String activityid) {
		RestClientProxy traceProxy = RestClientFactory.getAssignTraceClient();
		ITraceTicket traceTicket = traceProxy.getService(ITraceTicket.class);
		HashMap<String, Object> scopes = new HashMap<String, Object>();
		String page = null;
		try {
			RestResponse<Object> ticketExResp = traceTicket.getEntityDetail(itsmcode, QueryEntity.TICKET_EXTENSE.name(),
					ticketid, null);
			Map ticketEX = (Map) ticketExResp.getResult();
			Map<String, String> ticketExtpropsMap = JSONHelper.fromJSON(ticketEX.get("extprops").toString(), Map.class);
			scopes.put("ticketEx", ticketExtpropsMap);
			scopes.put("ticketId", ticketid);
			page = PageLoader.getPage("more/changeDate.html", scopes);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			page = e.getMessage();
		}
		return Response.ok(page, MediaType.TEXT_HTML_TYPE).build();
	}

	/**
	 * 如果用不到picker可以为null，picker为完成页面的选择器
	 * 
	 * @see com.lenovo.lmrp.api.appgateway.IAppPage#getDeviceInputPage(java.lang.String)
	 */
	@Override
	public Response getDeviceInputPage(String itsmcode, String picker) {
		HashMap<String, Object> scopes = new HashMap<String, Object>();
		scopes.put("picker", picker);
		String page = null;
		try {
			page = PageLoader.getPage("deviceInput.html", scopes);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			page = e.getMessage();
		}
		return Response.ok(page, MediaType.TEXT_HTML_TYPE).build();
	}

	@Override
	public Response getDeviceInfoPage(String itsmcode, String attId, String name, String id, String fru,
			String description) {
		HashMap<String, Object> scopes = new HashMap<String, Object>();
		scopes.put("id", attId);
		scopes.put("name", name);
		scopes.put("partNo", id);
		scopes.put("fruNo", fru);
		scopes.put("desc", description);
		String page = null;
		try {
			page = PageLoader.getPage("deviceInfo.html", scopes);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			page = e.getMessage();
		}
		return Response.ok(page, MediaType.TEXT_HTML_TYPE).build();
	}

	/**
	 * 格式化成页面需要的格式
	 * 
	 * @param dateString
	 *            pattern must be yyyy-MM-dd HH:mm:ss
	 * @return pattern MM/dd HH:mm
	 */
	private String format(String dateString) {
		String month = dateString.substring(5, 7);
		String day = dateString.substring(8, 10);
		String hourAndMinutes = dateString.substring(11, 16);

		return month + "/" + day + " " + hourAndMinutes;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.lenovo.lmrp.api.appgateway.IAppPage#getBreakOffPage(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public Response getBreakOffPage(String itsmcode, String ticketid) {
		String page = null;
		HashMap<String, Object> scopes = new HashMap<String, Object>();
		scopes.put("ticketId", ticketid);
		scopes.put("breakoffReason", CloseReason.values());
		try {
			page = PageLoader.getPage("more/breakoff.html", scopes);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			page = e.getMessage();
		}
		return Response.ok(page, MediaType.TEXT_HTML_TYPE).build();
	}

	/**
	 * 获取退单页面
	 */
	@Override
	public Response getBackOrderInfoPage(String itsmcode, String ticketid) {
		RestClientProxy traceProxy = RestClientFactory.getAssignTraceClient();
		ITraceTicket traceTicket = traceProxy.getService(ITraceTicket.class);
		HashMap<String, Object> scopes = new HashMap<String, Object>();
		String page = null;
		try {
			RestResponse<List<Map<String, String>>> restResponse = traceTicket.getProjectEngineers(itsmcode, ticketid);
			List<Map<String, String>> result = restResponse.getResult();
			scopes.put("engineerVOs", result);
			scopes.put("ticketId", ticketid);
			page = PageLoader.getPage("process/back_order.html", scopes);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			page = e.getMessage();
		}
		return Response.ok(page, MediaType.TEXT_HTML_TYPE).build();
	}
   
    /**
     * 获取工单详情设备信息和设备图片页面（4-换上件， 5-换下件）
     * @author zxx
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#getTicketParts(java.lang.String, java.lang.String)
     */
    @Override
    public Response getTicketParts(String itsmcode, String ticketid ,String id) {
        RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
        IItsmTicket itsmTicket = itsmProxy.getService(IItsmTicket.class);
        HashMap<String, Object> scopes = new HashMap<String, Object>();
        String page = null;
        try {
            RestResponse <List<PartsVO>> ticketPartsList = itsmTicket.listParts(itsmcode, ticketid);
            RestResponse <List<AttachmentVO>> partsAttachmentList = itsmTicket.listAttachment(itsmcode, ticketid, -1,"4,5");
            scopes.put("ticketPartsList", ticketPartsList.getResult());
            scopes.put("partsAttachmentList", partsAttachmentList.getResult());
            scopes.put("ticketid", ticketid);
            page = PageLoader.getPage("process/subpage/ticketdetails/ticketParts.html", scopes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            page = e.getMessage();
        }
        return Response.ok(page,MediaType.TEXT_HTML_TYPE).build();
    }
    
    /**
     * 获取工单详情设备信息
     * @author zxx
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#getParts(java.lang.String, java.lang.String, java.lang.String)
     */
    public Response getParts(String itsmcode, String ticketid ,String partnum) {
        RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
        IItsmTicket itsmTicket = itsmProxy.getService(IItsmTicket.class);
        HashMap<String, Object> scopes = new HashMap<String, Object>();
        String page = null;
        try {
            RestResponse<PartsVO> partsList = itsmTicket.getParts(itsmcode, ticketid, partnum);
            scopes.put("partsname", partsList.getResult().getPartsname());
            scopes.put("partsnum", partsList.getResult().getPartsnum());
            scopes.put("fru", partsList.getResult().getFru());
            scopes.put("desc", partsList.getResult().getDescription());
            scopes.put("ticketid", ticketid);
            page = PageLoader.getPage("process/subpage/ticketdetails/ticketPartsInfo.html", scopes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            page = e.getMessage();
        }
        return Response.ok(page,MediaType.TEXT_HTML_TYPE).build();
    }
    
    /**
     * 获取工单详情附件信息页面
     * @author zxx
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#getAttachmentInfo(java.lang.String, java.lang.String)
     */ 
    @Override
    public Response getAttachmentInfo(String itsmcode, String ticketid) {
        RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
        IItsmTicket itsmTicket = itsmProxy.getService(IItsmTicket.class);
        HashMap<String, Object> scopes = new HashMap<String, Object>();
        String page = null;  
        try {
            RestResponse <List<AttachmentVO>> attachmentList = itsmTicket.listAttachment(itsmcode, ticketid, -1,"0,1,2,3");
            scopes.put("attachmentList", attachmentList.getResult());
            page = PageLoader.getPage("process/subpage/ticketdetails/attachmentInfo.html", scopes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            page = e.getMessage();
        }
        return Response.ok(page,MediaType.TEXT_HTML_TYPE).build();
    }
    
    /**
     * 获取工单详情解决方案页面
     * @author zxx
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#getSolution(java.lang.String, java.lang.String)
     */
    @Override
    public Response getSolution(String itsmcode, String ticketid) {
        RestClientProxy itsmProxy = RestClientFactory.getAssignTraceClient();
        ITraceTicket iTraceTicket = itsmProxy.getService(ITraceTicket.class);
        HashMap<String, Object> scopes = new HashMap<String, Object>();
        String page = null;
        try {
            RestResponse<Object> ticketResp = iTraceTicket.getEntityDetail(itsmcode, QueryEntity.TICKET.name(),ticketid, null);
            RestResponse<Object> ticketExResp = iTraceTicket.getEntityDetail(itsmcode,QueryEntity.TICKET_EXTENSE.name(), ticketid, null);
          //组合页面所需数据
            Map ticketEX = (Map) ticketExResp.getResult();
            Map<String, String> ticketExtpropsMap = JSONHelper.fromJSON(ticketEX.get("extprops").toString(), Map.class);
            scopes.put("ticket", ticketResp.getResult());
            scopes.put("ticketEx", ticketExtpropsMap);
            page = PageLoader.getPage("process/subpage/ticketdetails/solution.html", scopes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            page = e.getMessage();
        }
        return Response.ok(page,MediaType.TEXT_HTML_TYPE).build();
    }
    
    /**
     * 获取巡检单详情页面
     * @author zx-lxj
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#getClosedTicketPage(java.lang.String, java.lang.String)
     */
    @Override
    public Response getInspectionTicketPage(String itsmcode, String ticketid) {
        RestClientProxy traceProxy = RestClientFactory.getAssignTraceClient();
        ITraceTicket traceTicket = traceProxy.getService(ITraceTicket.class);
        RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
        IItsmTicket itsmTicket = itsmProxy.getService(IItsmTicket.class);
        HashMap<String, Object> scopes = new HashMap<String, Object>();
        String page = null;
        try {
            //获取工单信息及扩展信息
            RestResponse<Object> ticketResp = traceTicket.getEntityDetail(itsmcode, QueryEntity.TICKET.name(),
                ticketid, null);
            RestResponse<Object> ticketExResp = traceTicket.getEntityDetail(itsmcode,
                QueryEntity.TICKET_EXTENSE.name(), ticketid, null);
            //组合页面所需数据
            Map ticketEX = (Map) ticketExResp.getResult();
            Map<String, String> ticketExtpropsMap = JSONHelper.fromJSON(ticketEX.get("extprops").toString(), Map.class);
            String respondLevel = ticketExtpropsMap.get("respondlevel");
            if (CommonUtil.nonNullAndEmpty(respondLevel)) {
				String[] respondLevelArr = respondLevel.split("[\\*]");
				String respondTime = respondLevelArr[respondLevelArr.length - 1];
				scopes.put("respondTime", respondTime);
			}
            //获取设备信息
            RestResponse <List<PartsVO>> ticketPartsList = itsmTicket.listParts(itsmcode, ticketid);
            RestResponse <List<AttachmentVO>> partsAttachmentList = itsmTicket.listAttachment(itsmcode, ticketid, -1,"4");
            scopes.put("ticketPartsList", ticketPartsList.getResult());
            scopes.put("partsAttachmentList", partsAttachmentList.getResult());
            scopes.put("ticketid", ticketid);
            //放入map
            scopes.put("ticket", ticketResp.getResult());
            scopes.put("ticketEx", ticketExtpropsMap);
            scopes.put("respondLevel", respondLevel);
            //获取页面
            page = PageLoader.getPage("process/inspectionTicketDetails.html", scopes);
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            page = e.getMessage();
        }
        return Response.ok(page, MediaType.TEXT_HTML_TYPE).build();
    }
    
    

    /* (non-Javadoc)
     * 获取已关单工单详情页
     * @author lin
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#getClosedTicketPage(java.lang.String, java.lang.String)
     */
    @Override
    public Response getClosedTicketPage(String itsmcode, String ticketid) {
        RestClientProxy traceProxy = RestClientFactory.getAssignTraceClient();
        ITraceTicket traceTicket = traceProxy.getService(ITraceTicket.class);
        RestClientProxy eventProxy = RestClientFactory.getEventRecorderClient();
        List<TicketEventPO> ticketEventPOs = new ArrayList<>();
		if(Objects.nonNull(eventProxy)){
			IEventQuery eventQuery = eventProxy.getService(IEventQuery.class);
			if(Objects.nonNull(eventQuery)){
				RestResponse<List<TicketEventVO>> ticketEvents = eventQuery.getTicketEvents(itsmcode, ticketid);
				List<TicketEventVO> result = ticketEvents.getResult();
				if (Objects.nonNull(result)) {
				    result.forEach(vo -> {
	                    TicketEventPO tpo = new TicketEventPO();
	                    tpo.setAction(vo.getAction().toLowerCase());
	                    tpo.setEventTime(vo.getEventtime());
	                    tpo.setTicketID(vo.getTicketid());
	                    try {
	                        tpo.setContent(JSONHelper.fromJSON(vo.getContent(), Map.class));
	                    } catch (Exception e) {
	                        log.error(e.getMessage(), e);
	                    }
	                    ticketEventPOs.add(tpo);
	                });
				}
			}
		}
        HashMap<String, Object> scopes = new HashMap<String, Object>();
        String page = null;
        try {
            //获取工单信息及扩展信息
            RestResponse<Object> ticketResp = traceTicket.getEntityDetail(itsmcode, QueryEntity.TICKET.name(),
                ticketid, null);
            RestResponse<Object> ticketExResp = traceTicket.getEntityDetail(itsmcode,
                QueryEntity.TICKET_EXTENSE.name(), ticketid, null);
           //组合页面所需数据
            Map ticketEX = (Map) ticketExResp.getResult();
            Map<String, String> ticketExtpropsMap = JSONHelper.fromJSON(ticketEX.get("extprops").toString(), Map.class);
            String respondLevel = ticketExtpropsMap.get("respondlevel");
            if (CommonUtil.nonNullAndEmpty(respondLevel)) {
				String[] respondLevelArr = respondLevel.replace("*", "x").split("x");
				String respondTime = respondLevelArr[respondLevelArr.length - 1];
				scopes.put("respondTime", respondTime);
			}
            //放入map
            scopes.put("ticket", ticketResp.getResult());
            scopes.put("ticketEx", ticketExtpropsMap);
            scopes.put("respondLevel", respondLevel);
            scopes.put("ticketEventPOs", ticketEventPOs);
            //获取页面
            page = PageLoader.getPage("process/closedTicketDetails.html", scopes);
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            page = e.getMessage();
        }
        return Response.ok(page, MediaType.TEXT_HTML_TYPE).build();
    }
    
    
    /**
     * 跳转上传附件页面
     * 
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#getUploadPage(java.lang.String, java.lang.String)
     */
    @Override
    public Response getUploadPage(String itsmcode, String ticketid) {
        HashMap<String, Object> scopes = new HashMap<String, Object>();
        String page = null;
        try {
            scopes.put("itsmcode", itsmcode);
            scopes.put("ticketId", ticketid); 
            page = PageLoader.getPage("process/subpage/common/uploadAttachment.html", scopes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            page = e.getMessage();
        }
        return Response.ok(page,MediaType.TEXT_HTML_TYPE).build();
    }
    /**
     * 获取关于页面
     * @author zx-lxj
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#getUploadPage(java.lang.String)
     */
    @Override
    public Response getAboutPage(@PathParam("itsmcode") String itsmcode){
        HashMap<String, Object> scopes = new HashMap<String, Object>();
        String page = null;
        try {
            page = PageLoader.getPage("about.html", scopes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            page = e.getMessage();
        }
        return Response.ok(page,MediaType.TEXT_HTML_TYPE).build();
    }
    
    
    /**
     * 获取项目组信息页面
     * @author zx-lxj
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#getProjectPage(java.lang.String, java.lang.String)
     */
    @Override
    public Response getProjectPage(String itsmcode, String ticketid) {
        HashMap<String, Object> scopes = new HashMap<String, Object>();
        String page = null;
        RestClientProxy assignTraceProxy = RestClientFactory.getAssignTraceClient();
        ITraceTicket iTraceTicket = assignTraceProxy.getService(ITraceTicket.class);
        RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
        try {
            RestResponse<List<Map<String, String>>> restResponse = iTraceTicket.getProjectEngineers(itsmcode, ticketid);
            List<Map<String, String>> result = restResponse.getResult();
            scopes.put("engineerVOs", result);
            scopes.put("ticketId", ticketid);
            
            IItsmProject iItsmProject = itsmProxy.getService(IItsmProject.class);
            RestResponse<ProjectPO> respeonse = iItsmProject.getProjectByTicketId(itsmcode, ticketid);
            if (respeonse.getEcode() == 0) {
            	scopes.put("project", respeonse.getResult());
            }
            page = PageLoader.getPage("process/projectInfo.html", scopes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            page = e.getMessage();
        }
        return Response.ok(page,MediaType.TEXT_HTML_TYPE).build();
    }
    
    /**
     * 创建巡检单ID,获取巡检单页面。
     * @author zx-lxj
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#getCreateTicketPage(java.lang.String)
     */
    @Override
    public Response getCreateTicketPage(String itsmcode) {
        // 获取工程师信息
        RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
        IItsmProject itsmProject =itsmProxy.getService(IItsmProject.class);
        
        HashMap<String, Object> scopes = new HashMap<String, Object>();
        String page = null;
        try {
            String engineerId = appsession.getLoginData().getLoginname();
            RestResponse <List<ProjectVO>> projectList = itsmProject.listEngineerProject(itsmcode,engineerId,"","","");
            String projectText ="[";
            for(int i = 0;i<projectList.getResult().size();i++){
                if(i==(projectList.getResult().size()-1)){
                    projectText +="{text:\""+projectList.getResult().get(i).getProjectId()
                                    +"_"+projectList.getResult().get(i).getProjectName()
                                    +"\",value:\""+projectList.getResult().get(i).getProjectId()
                                    +"_"+projectList.getResult().get(i).getProjectName()
                                    +"\",index:"+i+"}";
                }else{
                    projectText +="{text:\""+projectList.getResult().get(i).getProjectId()
                                    +"_"+projectList.getResult().get(i).getProjectName()
                                    +"\",value:\""+projectList.getResult().get(i).getProjectId()
                                    +"_"+projectList.getResult().get(i).getProjectName()
                                    +"\",index:"+i+"},";
                }
            }
            projectText +="]";
            
            scopes.put("projectText",projectText);
            scopes.put("engineerId",engineerId);
        } catch (Exception e) {
            log.warn("activepage get engineer info error.",e);
        }
        try {
            page = PageLoader.getPage("process/inspectionTicket.html", scopes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            page = e.getMessage();
        }
        return Response.ok(page,MediaType.TEXT_HTML_TYPE).build();
    }
    
    /**
     * 创建巡检单，返回历史工单页面
     * 
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#createInspectionTicket(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
    @Override
    public RestResponse<String> createInspectionTicket(String itsmcode,Map<String,String> fields) {
        RestResponse<String> response = null;
        try {
            TicketVO ticket = new TicketVO();                   
            ticket.setProject(fields.get("project").substring(0,fields.get("project").indexOf("_")));
            ticket.setTitle(fields.get("title"));
            Map<String, String> others = new HashMap<>();
            others.put("customerName",fields.get("customerName"));
            others.put("customerphone",fields.get("customerphone"));
            others.put("ChrUserID",fields.get("ChrUserID"));
            others.put("customeraddress",fields.get("customeraddress"));
            others.put("projectName",fields.get("project").substring(fields.get("project").indexOf("_")+1,fields.get("project").length()));
            // 获取工程师信息
            RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
            IItsmEngineer iItsmEngineer = itsmProxy.getService(IItsmEngineer.class);
            try {
                Response responseEngineer = iItsmEngineer.getEngineer(itsmcode,
                        appsession.getLoginData().getLoginname());
                RestResponse<EngineerVO> rest = responseEngineer.readEntity(RestResponse.class);
                EngineerVO engineer = (EngineerVO)rest.getResult(EngineerVO.class);  
                ticket.setAssignee(engineer.getLoginname());
                others.put("submiterFullname", engineer.getName()== null ? "" : engineer.getName()); 
                others.put("provinceName", engineer.getProvinceName()== null ? "" : engineer.getProvinceName()); 
                others.put("CityName", engineer.getCityName() == null ? "" : engineer.getCityName()); 
                others.put("County", engineer.getCounty()== null ? "" : engineer.getCounty()); 
                others.put("tickettype","2");
                responseEngineer.close();               
            } catch (Exception e) {
                log.warn("activepage get engineer info error.",e);
            }
            ticket .setOthers(others);
            //创建工单
            RestClientProxy clientProxy = RestClientFactory.getItsmGatewayClient();
            IItsmTicket itsmTicket = clientProxy.getService(IItsmTicket.class);
            response = itsmTicket.openTicket(itsmcode, ticket);
        } catch (Exception exp) {
            log.error("error when create ticket ticketid = {}", itsmcode, exp);
            response = new RestResponse<String>(1, "工单创建失败.", null);
        }
            return response;
    }
    
    /**
     * 跳转上传巡检设备信息页面
     * @author zx-lxj
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#getUploadPage(java.lang.String, java.lang.String)
     */
    @Override
    public Response getUploadDevicePage(String itsmcode, String ticketid) {
        HashMap<String, Object> scopes = new HashMap<String, Object>();
        String page = null;
        try {
            scopes.put("itsmcode", itsmcode);
            scopes.put("ticketId", ticketid); 
            page = PageLoader.getPage("process/subpage/inspectionticket/uploadDevice.html", scopes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            page = e.getMessage();
        }
        return Response.ok(page,MediaType.TEXT_HTML_TYPE).build();
    }
    /**
     * 保存巡检单设备信息
     * @author zx-lxj
     * @see com.lenovo.lmrp.api.appgateway.IAppPage#saveParts(java.lang.String, java.lang.String, com.lenovo.lmrp.api.model.view.ChangedTicketVO)
     */
    @Override
    public RestResponse<String> saveParts(String itsmcode,String ticketid,ChangedTicketVO changedVO){
        List<TicketPartsPO> partsPOs = new ArrayList<>(0);
        Map<String, String> params = changedVO.getFields();
        // 判断是否有收到输入备件信息
        String partsJson = params.get("addDevice");
        if (Objects.nonNull(partsJson)) // 将数据录入到备件集合
            partsPOs.addAll(parseToPartsPOList(partsJson, changedVO.getTicketid()));
        params.remove("addDevice");
        changedVO.setFields(params);
        syncItsm(itsmcode, ticketid, parseToPartsVO(partsPOs));
        RestResponse<String> response = new RestResponse<String>(0, "提交成功", null);
        return response;
    }
    
    // 将Json数据转换成集合
    private List<TicketPartsPO> parseToPartsPOList(String json, String ticketId) {
        List<TicketPartsPO> list = new ArrayList<>(0);
        try {
            if (CommonUtil.nonNullAndEmpty(json) && json.contains("[") && json.contains("]")) {// 多个数据
                // 替换格式
                json = json.replaceAll("\"\\{", "{").replaceAll("\\}\"", "}").replaceAll("\\\\", "");
                @SuppressWarnings("rawtypes")
                List fromJSON = JSONHelper.fromJSON(json, List.class);
                for (Object object : fromJSON) {
                    TicketPartsPO partsPO = JSONHelper.fromJSON(JSONHelper.toJSON(object), TicketPartsPO.class);
                    partsPO.setTicketId(ticketId);
                    list.add(partsPO);
                }
            } else if (CommonUtil.nonNullAndEmpty(json)) {// 单个数据
                TicketPartsPO partsPO = JSONHelper.fromJSON(json, TicketPartsPO.class);
                partsPO.setTicketId(ticketId);
                list.add(partsPO);
            }
            return list;
        } catch (Exception e) {
            throw new TraceableException(ErrorCode.COMM_PARSE_FAILED, e);
        }
    }
    
    // 将TicketPartsPO转换成PartsVO
    private List<PartsVO> parseToPartsVO(List<TicketPartsPO> partsPOs) {
        List<PartsVO> partsVOs = new ArrayList<>(0);
        for (TicketPartsPO ticketPartsPO : partsPOs) {
            PartsVO partsVO = new PartsVO();
            partsVO.setPartsnum(ticketPartsPO.getId());
            partsVO.setFru(ticketPartsPO.getFRU());
            partsVO.setPartsname(ticketPartsPO.getName());
            partsVO.setDescription(ticketPartsPO.getDescription());
            partsVO.setNew(true);
            partsVOs.add(partsVO);
        }
        return partsVOs;
    }

    // 同步数据（备件）到itsm系统
    private void syncItsm(String itsmcode,String ticketid, List<PartsVO> parts) {
        RestClientProxy proxy = RestClientFactory.getItsmGatewayClient();
        IItsmTicket itsmTicket = proxy.getService(IItsmTicket.class);
        itsmTicket.replaceParts(itsmcode,ticketid, parts);// 同步备件
    }
}
